import cv2
from ultralytics import YOLO

# Load a COCO-pretrained YOLO11n model
model = YOLO("/data/yolo11/gxhyolo/runs/detect/train8/weights/best.pt")

# Train the model on the COCO8 example dataset for 100 epochs
#results = model.train(data="/data/yolo11/gxhyolo/datasets/gxh.yaml", epochs=1000, imgsz=640)

# Load an image from file
#image_path = "/data/yolo11/gxhyolo/datasets/gxh/images/test/test01.png"
#image = cv2.imread(image_path)
cap = cv2.VideoCapture(1)

# Check if the camera was opened successfully
if not cap.isOpened():
    print("Error: Could not open camera.")
    exit()
    
# Loop to continuously capture frames from the camera

# Load a COCO-pretrained YOLO11n model
model = YOLO("/data/yolo11/gxhyolo/runs/detect/train8/weights/best.pt")

while True:
    # Capture frame-by-frame
    ret, frame = cap.read()

    # If frame is read correctly, ret is True
    if not ret:
        print("Error: Failed to capture image.")
        break

    results = model( frame )
    #results[0].show()

    for result in results:
    
        boxes = result.boxes  # Get the bounding boxes
        print("===========================" )
        for box in boxes:
            # Get the coordinates of the bounding box
            x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
        
            # Calculate the center coordinates
            center_x = int((x1 + x2) / 2)
            center_y = int((y1 + y2) / 2)
        
            # Print the center coordinates
            print("        ????????????????????????????" )
            print(f"          Center coordinates of the detected object: ({center_x}, {center_y})")
        
            # Optionally, draw the center on the image
            cv2.circle(frame, (center_x, center_y), 25, (0, 0, 255), 2)

    cv2.imshow("Detected Objects", frame)
    if cv2.waitKey(100) & 0xFF == ord('q'):
        break
    

cv2.destroyAllWindows()

cap.release()
cv2.destroyAllWindows()
